/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.common.utils;

import com.chinamobile.cmss.lakehouse.common.Constants;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setDateFormat(new SimpleDateFormat(Constants.DATE_FORMAT_PATTERN));
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * JSON 字符串反序列化为对象
     *
     * @param jsonMap
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T mapToObject(Map<String, Object> jsonMap, Class<T> valueType) {
        try {
            return objectMapper.readValue(objectToString(jsonMap), valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String objectToString(Object obj) throws JsonProcessingException {
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * @param valueType
     * @return
     */
    public static Map<String, Object> toMap(Object valueType) {
        try {
            return objectMapper.readValue(objectMapper.writeValueAsString(valueType), Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new HashMap<>(10);
    }
}
